<template>
    <div class="content_container">
        <div class="left_container management">
            <div class="title_management">
                <h2>新增菜单</h2>
            </div>
            <div class="content_management">
                <el-button size="mini" type="primary"
                    style="margin: 0 0 20px 20px;width: 110px;height: 40px;font-size: 17px;" @click="handleAdd(null)"
                    v-if="role === '超级管理员' || role === '管理员'">新增目录</el-button>
                <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id" border default-expand-all
                    :tree-props="{ children: 'childMenuList', hasChildren: 'hasChildren' }" :header-cell-style="getRowClass"
                    :row-class-name="tableRowClassName">
                    <el-table-column label="菜单名称" prop="pageName" sortable align="left">
                    </el-table-column>
                    <el-table-column label="页面编码" sortable align="center">
                        <template slot-scope="scope">
                            {{ scope.row.pageType == '目录' ? '-' : scope.row.pageCode }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="pageType" label="类型" align="center">
                    </el-table-column>
                    <el-table-column label="操作" align="center" min-width="200px">
                        <template slot-scope="scope">
                            <!-- 新增 -->
                            <el-tooltip class="item" effect="dark" content="新增" placement="top">
                                <el-button size="mini" type="warning" @click="handleAdd(scope.row)"
                                    v-if="scope.row.pageType == '目录'" plain icon="el-icon-plus"></el-button>
                            </el-tooltip>
                            <!-- 编辑 -->
                            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                                <el-button size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit"></el-button>
                            </el-tooltip>
                            <!-- 状态 -->
                            <el-tooltip class="item" effect="dark" content="管理" placement="top">
                                <!-- scope.row.status == '1' && -->
                                <el-button size="mini" type="primary" @click="publish(scope.row)"
                                    v-if="scope.row.pageType !== '目录'" icon="el-icon-more-outline"></el-button>
                            </el-tooltip>
                            <!-- 菜单配置 -->
                            <el-tooltip class="item" effect="dark" content="菜单配置" placement="top">
                                <el-button size="mini" type="info" @click="handleConfig(scope.row)"
                                    v-if="scope.row.pageType == '菜单' && scope.row.status != '2'"
                                    icon="el-icon-s-operation"></el-button>
                            </el-tooltip>
                            <!-- 测试 -->
                            <el-tooltip class="item" effect="dark" content="测试" placement="top">
                                <el-button size="mini" @click="handleTest(scope.row)"
                                    v-if="scope.row.pageType == '菜单' && scope.row.status == '1'"
                                    icon="el-icon-mouse"></el-button>
                            </el-tooltip>
                            <!-- 删除 -->
                            <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
                                    icon="el-icon-delete"></el-button>
                            </el-tooltip>
                            <!-- 分享 -->
                            <el-tooltip class="item" effect="dark" content="分享" placement="top">
                                <el-button size="mini" type="warning" @click="handleShare(scope.row)"
                                    icon="iconfont icon-fenxiang1" v-if="scope.row.pageType == '菜单'"></el-button>
                            </el-tooltip>
                            <!-- <el-button size="mini" type="info" @click="publish(scope.row)"
                                v-if="scope.row.status == '2' && scope.row.pageType !== '目录'" plain>撤回</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
                <!-- sharePage 管理员创建 status 0 可以发布（可编辑）  1 可以撤回（不能编辑） -->
            </div>
        </div>
        <!-- 菜单编辑 -->
        <el-drawer :title="drawerTitle" :visible.sync="drawer" :direction="direction1" size="30%" >
            <el-form ref="menuEditForm" :model="form" :rules="rules" label-width="120px" label-position="left"
                style="padding-left:25px;">
                <el-form-item label="菜单名称" v-if="form.type == '菜单'" prop="pageName">
                    <el-input v-model.trim="form.pageName" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="目录名称" v-else prop="pageName">
                    <el-input v-model.trim="form.pageName" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="图标选择" v-if="form.type == '目录'" prop="pageIcon">
                    <div class="icon_Select">
                        <div class="icon_replace" @click="iconSelectClick">
                            <i class="iconfont" :class="form.pageIcon" style="font-size:25px;z-index:110;"></i>
                            <i class="el-icon-arrow-down"></i>
                        </div>
                        <el-select v-model="form.pageIcon" placeholder="请选择图标"
                            style="transform:translateY(-40px);opacity:0;" ref="iconSelect">
                            <el-option v-for="item in iconOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                                <i class="iconfont" :class="item.value" style="font-size:25px;"></i>
                            </el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="菜单编码" v-if="form.type == '菜单'" prop="pageCode">
                    <el-input v-model.trim="form.pageCode" style="width: 200px;"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="访问地址" prop="visitAddress">
                    <el-input v-model.trim="form.visitAddress" style="width: 200px;"></el-input>
                </el-form-item> -->
                <el-form-item label="菜单类型" prop="configType" v-if="this.drawerTitle == '新增菜单'">
                    <el-select v-model="form.configType" placeholder="请选择菜单版本" clearable @change="init">
                        <el-option label="新版" value="new" />
                        <el-option label="老版" value="old" />
                    </el-select>
                </el-form-item>

                <el-form-item label="克隆配置" v-if="cloneFlag && this.drawerTitle == '新增菜单'">
                    <el-select v-model="form.cloneConfig" placeholder="请选择克隆的菜单" clearable @change="changeClone">
                        <el-option v-for="item in menuList" :key="item.pageCode" :label="item.name" :value="item.pageCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="saveMenuList">保存</el-button>
            </el-form>
        </el-drawer>

        <!-- 菜单配置(旧) -->
        <el-drawer :visible.sync="drawer_old" :direction="direction2" size="80%" :close-on-press-escape="false"
            :before-close="beforeClose" v-if="drawer_old">
            <template slot="title">
                <div class="title_drawer">
                    <h3>
                        菜单配置
                        <el-tooltip class="item" effect="dark" content="使用说明" placement="top">
                            <span class="breach_div_icon">
                                <i class="el-icon-question"></i>
                            </span>
                        </el-tooltip>
                    </h3>
                    <el-button type="primary" style="margin-right: 20px;" @click="recordsConfig">记录</el-button>
                </div>
            </template>
            <oldConfig :editRow="editRow" ref="oldMenuConfig" />
        </el-drawer>

        <!-- 菜单配置(新) -->
        <el-drawer :visible.sync="drawer_new" :direction="direction" size="80%" :show-close="false"
            :before-close="handleCloseNew" v-if="drawer_new">
            <template slot="title">
                <div class="title_drawer_new">
                    <h4>
                        菜单配置
                        <el-tooltip class="item" effect="dark" content="使用说明" placement="top">
                            <span class="breach_div_icon">
                                <i class="el-icon-question"></i>
                            </span>
                        </el-tooltip>
                    </h4>
                </div>
            </template>
            <menuConfig :editRow="editRow" ref="menuConfig" @saveMenu="saveMenu" />
        </el-drawer>

        <el-dialog title="菜单状态" :visible.sync="publishVisible" width="400px" :close-on-press-escape="false"
            :close-on-click-modal="false" v-dialogDrag>
            <el-radio-group v-model="menuConfigFrom.publishTypeCode">
                <el-radio :label="item.publishTypeCode" v-for="item in publishList" :key="item.publishTypeCode"
                    style="margin:0 15px 15px 0" :disabled="!item.enable">{{ item.publishTypeName }}</el-radio>
                <!-- <el-radio :label="1">公共平台</el-radio>
                <el-radio :label="2">暂不发布</el-radio> -->
            </el-radio-group>
            <div v-if="menuConfigFrom.publishTypeCode === 'role'">
                <el-select v-model="menuConfigFrom.roleIdList" placeholder="请选择角色" multiple collapse-tags>
                    <el-option v-for="item in RoleSelectList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <!-- <span>这是一段信息</span> -->
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="publishVerify" size="small">确 定</el-button>
                <el-button @click="publishVisible = false" size="small">取 消</el-button>
            </span>
        </el-dialog>

        <el-dialog title="分享" :visible.sync="ShareVisible" width="600px" :close-on-click-modal="false"
            :close-on-press-escape="false" v-dialogDrag>
            <div class="share_dom">
                <el-input placeholder="请输入分享用户" v-model.trim="shareName" clearable />
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addShareName"
                    :disabled="!shareName"></el-button>
            </div>
            <el-table :data="ShareData" style="width: 100%" :header-cell-style="getRowClass">
                <el-table-column prop="userName" label="分享用户" align="center">
                </el-table-column>
                <el-table-column prop="shareTime" label="分享时间" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="deleteShare(scope.row.shareUserId)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="shareConfirm">确 定</el-button>
                <el-button @click="ShareVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { deepClone } from '@/utils'
import oldConfig from './oldConfig'
import {
    getDrawPageListRequest,
    addDirectoryRequest,
    modifyDirectoryRequest,
    deleteDirectoryRequest,
    addMenuRequest,
    modifyMenuRequest,
    deleteMenuRequest,
    saveMenuSettingRequest,
    getCloudPicturePublishChooseOptionRequest,
    updateCloudPicturePublishStatusRequest
} from '@/api/user'
import {
    getRoleSelectListRequest,
    getHasShareUserListRequest,
    modifyShareUserRequest,
    searchShareUserInfoRequest
} from '@/api/management'
import {
    getCloneMenuListRequest,
    getNewConfigCloneMenuListRequest,
    saveCloudToolConfigRequest
} from '@/api/tools'
export default {
    name: 'GenecloudUiPage2',
    components: { oldConfig },
    data() {
        return {
            api: null,
            direction: 'ltr',
            shareName: null,
            ShareVisible: false,
            ShareData: [],
            shareFrom: {
                pictureId: null,
                shareUserIdList: []
            },
            RoleSelectList: [],
            publishList: [],
            menuConfigFrom: {
                pictureId: null,
                publishTypeCode: 0,
                roleIdList: []
            },
            cloneFlag: false,
            drawerTitle: '新增目录',
            maxHeight: `600px`,
            loading: true,

            drawer: false,
            direction1: 'rtl',
            drawer_old: false,
            direction2: 'ltr',
            tableData: [],
            form: {
                id: null,
                // pageCode: null,
                pageName: null,
                cloneConfig: null,
                icon: null,
                pageIcon: null,
                configType: 'new',
                // visitAddress: null,
                // directoryId: null,
            },
            menuList: [],
            editId: null,
            request: null,
            publishVisible: false,
            //校验
            rules: {
                pageName: [
                    { required: true, message: '请填写菜单', trigger: 'blur' },
                ],
                pageIcon: [
                    { required: true, message: '请选择图标', trigger: 'blur' },
                ],
                configType: [
                    { required: true, message: '请选择配置版本', trigger: 'blur' },
                ],
                // pageCode: [
                //     { required: true, message: '请填写菜单编码', trigger: 'blur' },
                // ],
                // visitAddress: [
                //     { required: true, message: '请填写地址', trigger: 'blur' },
                // ]
            },
            flag: false,
            editRow: null,
            iconOptions: this.$publicData('iconOptions'),
            role: JSON.parse(localStorage.getItem('userInfo')).role,
            drawer_new: false
        };
    },
    created() {
        setTimeout(() => {

            const event = document.createEvent('HTMLEvents');

            event.initEvent('resize', true, true);

            event.eventType = 'message'
            window.dispatchEvent(event);

        }, 100)
        window.addEventListener('resize', this.windowResize)
        this.getList()
    },

    beforeDestroy() {
        window.removeEventListener('resize', this.windowResize)
    },
    methods: {
        changeClone(value) {
            this.form.cloneConfig = value
            this.$forceUpdate()
        },
        async init(value) {
            this.api = value === 'new' ? getNewConfigCloneMenuListRequest : getCloneMenuListRequest
            //获取可克隆菜单列表
            const res = await this.api()
            if (res.code !== 200) return this.$message.error(res.message)
            this.menuList = res.data
            this.form.cloneConfig = ''
        },
        async getList() {
            const res = await getDrawPageListRequest()
            if (res.code !== 200) return this.$message.error(res.message)
            this.tableData = res.data
        },

        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        },
        handleAdd(row) {
            this.cloneFlag = true
            this.form = {}
            this.drawerTitle = row ? '新增菜单' : '新增目录'
            this.drawer = true
            this.form.type = row ? '菜单' : '目录'
            this.form.directoryId = row ? row.id : null
            this.request = row ? addMenuRequest : addDirectoryRequest
        },
        handleEdit(row) {
            this.cloneFlag = false
            const { pageType } = row
            this.form = deepClone(row)
            this.drawerTitle = pageType === '目录' ? '编辑目录' : '编辑菜单'
            this.form.type = pageType === '目录' ? '目录' : '菜单'
            this.drawer = true
            this.request = pageType === '目录' ? modifyDirectoryRequest : modifyMenuRequest
        },
        //发布撤回
        async publish(row) {
            const roles = await getRoleSelectListRequest()
            if (roles.code !== 200) return this.$message.error(res.message)
            this.RoleSelectList = roles.data
            this.menuConfigFrom.pictureId = row.id
            let pictureId = row.id
            const res = await getCloudPicturePublishChooseOptionRequest({ pictureId })
            if (res.code !== 200) return this.$message.error(res.message)
            this.publishVisible = true
            this.publishList = res.data
            let item = this.publishList.find(i => i.isChecked)
            this.menuConfigFrom.publishTypeCode = item.publishTypeCode
        },
        async handleDelete(row) {
            let prompt = row.pageType == '菜单' ? `此操作将永久删除该菜单, 是否继续?` : `此操作将永久删除该目录（包含所有子菜单）, 是否继续?`
            this.$confirm(prompt, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        let id = row.id
                        let res
                        if (row.pageType == '菜单') {
                            res = await deleteMenuRequest({ id })
                        } else {
                            res = await deleteDirectoryRequest({ id })
                        }
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.$message({
                            type: 'success',
                            message: res.message
                        })
                        this.getList()
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        saveMenuList() {
            this.$refs['menuEditForm'].validate(async valid => {
                if (valid) {
                    // let path = this.form.visitAddress.substring(0, 1)
                    // if (path !== '/') {
                    //     this.form.visitAddress = '/' + this.form.visitAddress
                    // }
                    const res = await this.request(this.form)
                    if (res.code !== 200) return this.$message.error(res.message)
                    this.$message({
                        type: 'success',
                        message: res.message
                    })
                    this.form = {
                        id: null,
                        pageCode: null,
                        pageName: null,
                        visitAddress: null,
                        directoryId: null,
                    }
                    this.getList()
                    this.drawer = false
                }
            })
        },
        async handleConfig(row) {
            this.editRow = deepClone(row)
            if (row.configType === 'new') {
                this.drawer_new = true
            } else {
                this.flag = false
                this.drawer_old = true
            }
        },

        beforeClose(done) {
            if (!this.flag) {
                this.$confirm('是否记录本次操作？')
                    .then(_ => {
                        this.$refs.oldMenuConfig.$refs['menuConfigForm'].validate((valid) => {
                            if (valid) {
                                this.recordsConfig()
                                done();
                            }
                        })
                    })
                    .catch(_ => {
                        this.$message('取消操作！')
                        this.$refs.oldMenuConfig.menuConfigForm = {
                            title: null,
                            fileForm: {},
                            fileList: [],
                            configList: [],
                            configForm: {},
                            downloadItem: [],
                            initialIsGroup: [],
                            initialIsGroupY: [],
                            tips: null,
                        }
                        this.$refs.oldMenuConfig.downloadItems = null
                        this.$refs.oldMenuConfig.documentRadio = 'select'
                        done();
                    });
            } else {
                done();
            }
        },
        windowResize() {
            let val = document.body.clientHeight
            this.maxHeight = (val - 350) + 'px'
        },
        //table 自定义表头
        getRowClass({ rowIndex, columnIndex }) {
            if (rowIndex == 0) {
                return "background:#eee;font-weight: 400;color:#666;text-align:center";
            }
        },
        tableRowClassName({ row, rowIndex }) {
            if (row.pageType === '目录') {
                return 'warning-row';
            }
            return '';
        },
        //记录菜单配置
        recordsConfig() {
            this.$refs.oldMenuConfig.$refs.menuConfigForm.validate(async (valid) => {
                if (valid) {
                    const res = await saveMenuSettingRequest({
                        id: this.editRow.id,
                        pageContent: JSON.stringify(this.$refs.oldMenuConfig.menuConfigForm)
                    })
                    if (res.code !== 200) return this.$message.error(res.message)
                    this.$message({
                        type: 'success',
                        message: res.message
                    })
                    this.flag = true
                    this.drawer_old = false
                    this.getList()
                }
            })

        },

        //测试
        handleTest(row) {
            let path = row.configType === 'new' ? 'testAnaly' : 'testPage'
            console.log(window.location.origin, 'window.location.origin');
            window.open(`${this.$url(window.location.origin)}/${path}?pageCode=${row.id}&page=editMenu`)
        },

        //分享
        async handleShare(row) {
            this.shareName = ''
            let pictureId = row.id
            this.shareFrom.pictureId = row.id
            const res = await getHasShareUserListRequest({ pictureId })
            if (res.code !== 200) return this.$message.error(res.message)
            this.ShareData = res.data
            this.ShareVisible = true
        },
        //删除分享用户
        deleteShare(id) {
            this.$confirm('该操作将取消与该用户的分享，是否继续？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        let index = this.ShareData.findIndex(i => i.shareUserId === id)
                        this.ShareData.splice(index, 1)
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        async addShareName() {
            let searchKeyword = this.shareName
            const res = await searchShareUserInfoRequest({ searchKeyword })
            if (res.code !== 200) return this.$message.error(res.message)
            this.ShareData.push(res.data)
        },
        //修改分享用户
        async shareConfirm() {
            this.shareFrom.shareUserIdList = this.ShareData.reduce((pre, item, index) => {
                pre.push(item.shareUserId)
                return pre
            }, [])
            const res = await modifyShareUserRequest(this.shareFrom)
            if (res.code !== 200) return this.$message.error(res.message)
            this.$message({
                type: 'success',
                message: res.message
            })
            this.ShareVisible = false
        },
        handleCloseNew(done) {
            this.$confirm('是否记录页面配置！', '提示')
                .then(_ => {
                    let menuForm = this.$refs.menuConfig.menuForm
                    this.saveMenu(menuForm)
                    done();
                })
                .catch(_ => {
                    done();
                });
        },
        async saveMenu(value) {
            let pageConfig = {
                pageCode: this.editRow.pageCode,
                ...value
            }
            // localStorage.setItem('cloudPictureConfig', JSON.stringify(value))
            // window.open('/cloudPictureView')
            const res = await saveCloudToolConfigRequest(pageConfig)
            if (res.code !== 200) return this.$message.error(res.message)
            this.$message({ type: 'success', message: res.message })
            localStorage.setItem('valid', JSON.stringify([]))
            this.drawer_new = false
            this.getList()
        },
        async publishVerify() {
            const res = await updateCloudPicturePublishStatusRequest(this.menuConfigFrom)
            if (res.code !== 200) return this.$message.error(res.message)
            this.$message({
                type: 'success',
                message: res.message
            })
            this.publishVisible = false
            this.getList()
        },
        iconSelectClick() {
            this.$refs.iconSelect.toggleMenu()
        },
    },
};
</script>

<style lang="scss" scoped>
@import "./editMenu.scss";
</style>